/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Gastos;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.sql.Statement;
import java.sql.ResultSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author nan
 */
public class gastosListar implements ActionListener, KeyListener{

    private Conexion.ConexionBD conectar = new Conexion.ConexionBD();
    private gastosListarGUI ventana = new gastosListarGUI();
    private Gastos.MedGastos gastos;
    private DefaultTableModel dtmGasto;

    public gastosListar(){
        ventana.setLocationRelativeTo(null);
        ventana.setActionListeners(this);
        ventana.setKeyListener(this);
        ventana.setVisible(true);
        actualizarTabla();
    }

    public void actualizarTabla(){
        String[] titulos = {"IDGasto", "Descripcion", "Fecha", "Gasto"};
        Object[][] datos = {};
        dtmGasto = new DefaultTableModel(datos, titulos);

        conectar.conectar();
        Statement st;
        try {
            st = conectar.getConn().createStatement();
            String consulta = "SELECT * FROM \"Gastos\"";
            ResultSet rs = st.executeQuery(consulta);
            String id = null;
            while (rs.next()){
                Object[] fila = {rs.getString(1),
                rs.getString(2),
                rs.getString(3),
                rs.getString(4)};
                dtmGasto.addRow(fila);
            }
        } catch (Exception e){
            e.printStackTrace();
        }
        getVentana().getjTableArticulos().setModel(dtmGasto);
    }

    public double actualizarPorCampo(String FechaD,String FechaH){
        String[] titulos = {"IDGasto", "Descripcion", "Fecha", "Gasto"};
        Object[][] datos = {};
        dtmGasto = new DefaultTableModel(datos, titulos);

        int cant = 0;
        double total = 0;
        conectar.conectar();
        Statement st;
        try {
            st = conectar.getConn().createStatement();
            String consulta = "SELECT * FROM \"Gastos\" WHERE \"Fecha\">='"+FechaD+"' AND \"Fecha\" <= '"+FechaH+"';" ;
            ResultSet rs = st.executeQuery(consulta);
            String id = null;
            while (rs.next()){
                Object[] fila = {rs.getString(1),
                rs.getString(2),
                rs.getString(3),
                rs.getString(4)};
                total = total + rs.getDouble(4);
                dtmGasto.addRow(fila);
                cant = cant +1;
            }
        } catch (Exception e){
            e.printStackTrace();
        }
        conectar.cerrar();
        getVentana().getjTableArticulos().setModel(dtmGasto);
        return total;
    }

    public boolean esFecha(String fech){
        Pattern p;
        p = Pattern.compile("^(31|30|2[0-9]{1}|1[0-9]{1}|0[1-9]{1})/(0[1-9]{1}|1[0-2]{1})/[0-9]{4}$");
        Matcher m = p.matcher(fech);
        return m.matches();
    }

    public void actionPerformed(ActionEvent e) {
        int select = getVentana().getjTableArticulos().getSelectedRow();
        if (e.getSource() == getVentana().getjButtonAgregar()){
            if (gastos == null){
                gastos = new MedGastos(this);
            } else {
                gastos.setVisible(true);
            }
        } else if (e.getSource() == getVentana().getjButtonMostrarTodos()){
            actualizarTabla();
            getVentana().getjTextFieldfechad().setText("");
            getVentana().getjTextFieldfechah().setText("");
        } else if (e.getSource() == getVentana().getjButtonEliminar()){
            eliminar(select);
        } else 
         if (e.getSource() == getVentana().getjButtonMostrarCampo()){
            String fechad = getVentana().getjTextFieldfechad().getText();
            String fechah =getVentana().getjTextFieldfechah().getText();
            if (esFecha(fechad)&esFecha(fechah)){
                actualizarPorCampo(fechad,fechah);
                getVentana().getjTextFieldfechad().setText("");
                getVentana().getjTextFieldfechah().setText("");
            }else{
                JOptionPane.showMessageDialog(null, "Ingrese dd/mm/aaaa", "Ingrese fecha", JOptionPane.INFORMATION_MESSAGE);

            }

        }
        if (e.getSource() == getVentana().getjButtonSalir()){
            getVentana().dispose();
        }
    }

    private void eliminar(int select){
        if (select != -1){
            String a = dtmGasto.getValueAt(select, 0).toString();

            conectar.conectar();
            int confirmado = JOptionPane.showConfirmDialog(null,"¿Está seguro que desea eliminar el Gasto?", "Eliminar Gastos", JOptionPane.YES_NO_OPTION);

            if (JOptionPane.OK_OPTION == confirmado){
                try {
                    Statement st = conectar.getConn().createStatement();
                    System.out.println(a);
                    String borrar = "DELETE FROM \"Gastos\" WHERE \"IDGastos\" = '"+a+"';";
                    System.out.println(st.execute(borrar));
                    st.close();
                } catch (Exception ex) {   
                    ex.printStackTrace();
                }
                conectar.cerrar();
                this.actualizarTabla();
                JOptionPane.showMessageDialog(null, "Se ha eliminado el Gasto", "Elemento eliminado", JOptionPane.INFORMATION_MESSAGE);
            }
        } else {
            JOptionPane.showMessageDialog(null, "Debe seleccionar un elemento", "Error por seleccion nula", JOptionPane.ERROR_MESSAGE);
        }
    }

    public void keyTyped(KeyEvent e) {

    }

    public void keyPressed(KeyEvent e) {   }

    public void keyReleased(KeyEvent e) {   }

    public void setVisible(boolean b) {
        getVentana().setVisible(b);
    }

    /**
     * @return the ventana
     */
    public gastosListarGUI getVentana() {
        return ventana;
    }

}
